<?php

    // 定义一个类
    class Db{
        private $host;
        private $root;
        private $pwd;
        private $dbname;
        private $port;
        private $charset;
        public $link; // 数据库对象
        public function __construct($parmas)
        {
            // 初始化属性
            $this->init($parmas);
            // 创建数据库对象
            $this->connect();
        }
        private function init($parmas=array()){
            $this->host = $parmas['host']??'localhost'; // isset($parmas['host'])?$parmas['host]:'localhost';
            $this->root = $parmas['root']??'root';
            $this->pwd = $parmas['pwd']??'root';
            $this->dbname = $parmas['dbname'];
            $this->port = $parmas['port']??'3306';
            $this->charset = $parmas['charset']??"utf8";
        }
        //创建数据库对象
        private function connect(){
            $this->link=@mysqli_connect($this->host,$this->root,$this->pwd,$this->dbname,$this->port);
            if(!$this->link){
                echo "数据库连接失败".mysqli_connect_error();
                exit;
            }
            // 设置字符集
            mysqli_set_charset($this->link,$this->charset);
        }
        // 执行增，删，改，查
        public function execute($sql){
            if(!$str = mysqli_query($this->link,$sql)){
                echo 'SQL语句执行错误'.mysqli_error($this->link);
                echo "<br>错误的SQL语句是".$sql;
                exit;
            }
            return $str;
        }
        // 查询
        public function select($sql,$type="num"){
            $result = $this->execute($sql);
            $type = $this->getType($type);
            if(mysqli_num_rows($result)>0){
                // echo $type;
                return mysqli_fetch_all($result,$type);
            }
        }
        // 查询返回数组类型
        private function getType($type="MYSQLI_ASSOC"){
            if($type=="asso"){
                $type = MYSQLI_ASSOC;
            }else if($type=="num"){
                $type = MYSQLI_NUM;
            }else{
                $type = MYSQLI_BOTH;
            }
            return $type;
        }
    }
    // 测试
    // $str = [
    //     'host'=>'127.0.0.1',
    //     "root"=>"root",
    //     "pwd"=>"root",
    //     "dbname"=>"test"
    // ];
    // $stu = new Db($str);
    // // $sql = "insert into user values(null,'zhangsan','10')";
    // // $stu->execute($sql);
    // // var_dump($stu->execute($sql));
    // $sql = 'select * from user where id=1';
    // var_dump($stu->select($sql,"num"));
?>